package updater.gui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.concurrent.ExecutionException;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;

import updater.control.FileDownloader;

public class Launcher extends JFrame implements ActionListener, PropertyChangeListener {

	private Preferences preferences;
	private UpdatePreferences updatePreferences;

	private FileDownloader updatePreferencesDownloader;
	
	private JButton update;
	private JButton exit;
	private JButton launchApplication;
	private JTextArea info;
	
	public Launcher() {

		setDefaultCloseOperation(EXIT_ON_CLOSE);
		
		preferences = new Preferences();
		buildGUI();

		setVisible(true);

		updatePreferencesDownloader = new FileDownloader(preferences.getUpdateUrl(), "update_preferences.xml");
		updatePreferencesDownloader.addPropertyChangeListener(this);
		
		updatePreferencesDownloader.execute();
	}

	private void buildGUI() {

		update = new JButton("Update");
		update.addActionListener(this);

		exit = new JButton("Exit");
		exit.addActionListener(this);

		launchApplication = new JButton("Start application");
		launchApplication.addActionListener(this);
		
		info = new JTextArea();
		info.setEditable(false);
		
		this.add(info);
		pack();
	}

	public static void main(String[] args) {

		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				new Launcher();
			}
		});
	}

	@Override
	public void actionPerformed(ActionEvent e) {

	}

	@Override
	public void propertyChange(PropertyChangeEvent evt) {

		if(updatePreferencesDownloader == evt.getSource()) {
			System.out.println(evt.getPropertyName() + " " + evt.getNewValue());
			
			String property = evt.getPropertyName();
			String value = "" + evt.getNewValue();
			
			if("state".compareToIgnoreCase(property) == 0) {
				
				if("DONE".compareToIgnoreCase(value) == 0) {
					
					try {
						switch(updatePreferencesDownloader.get()) {
						case FAILED:
							info.append("Update not available.");
							break;
						case FINISHED_SUCCESSFULLY:
						    UpdatePreferences up = new UpdatePreferences();
						    info.append("Found update: " + up.getValue(UpdatePreferences.VERSION_CODE_TAG));
							break;
						}
					} catch (InterruptedException e) {
						e.printStackTrace();
					} catch (ExecutionException e) {
						e.printStackTrace();
					}
				}
				
				
			} else if("progress".compareToIgnoreCase(property) == 0) {
				
			}
		}
		
	}

}
